﻿/// <reference path="../jquery-3.6.0.js" />

var isChangeModel = $("#fmodel").text() == "Change";
var SubDelFiles = [];
var DetDelFiles = [];

$(".many-uploader").change(manyUploaderChange);

$(".close-btn").click(closeBtnClick);

$(".single-uploader").change(function (e) {
    var tag = e.target;
    var reader = new FileReader();
    reader.readAsDataURL(tag.files[0]);
    reader.onload = function () {
        $(tag).parent().addClass("selectOver");
        $(tag).prev().attr("src", this.result).show();
    }
})

$("#gform").submit(function (e) {
    e.preventDefault();
    if ($("#s_select")[0].selectedIndex == 0) {
        window.alert("请选择分类信息");
        return;
    }
    var formdata = new FormData($("#gform")[0]);
    var subdoms = $(".g-subimgs .sub-uploader");
    var detdoms = $(".g-detimgs .det-uploader");
    //提取商品附属图集
    for (var i = 0; i < subdoms.length; i++) {
        var dom = subdoms.get(i);
        if (dom.files.length > 0) {
            formdata.append("Subimgs", dom.files[0]);
        }
    }
    //提取商品详情图集
    for (var i = 0; i < detdoms.length; i++) {
        var dom = detdoms.get(i);
        if (dom.files.length > 0) formdata.append("Detimgs", dom.files[0]);
    }
    //提取商品分类id
    var dom = $("#s_select")[0];
    var tid = JSON.parse(dom.options[dom.selectedIndex].value).typeid;
    formdata.append("Typeid", tid);
    //获取是否上架
    var bol = $("#good-enable").is(":checked");
    formdata.append("Enable", bol);

    if (isChangeModel) {
        //获取在服务端被删除的文件路径
        for (var i = 0; i < SubDelFiles.length; i++) formdata.append("SubDelFiles", SubDelFiles[i]);
        for (var i = 0; i < DetDelFiles.length; i++) formdata.append("DetDelFiles", DetDelFiles[i]);
    }

    $.ajax({
        url: isChangeModel ? "SetGood" : "AddNewGood",
        method: "POST",
        data: formdata,
        cache: false,//上传文件无需缓存
        processData: false,//用于对data参数进行序列化处理 这里必须false
        contentType: false,
        dataType: "json",
        success: function (res) {
            if (res.isucc) {
                window.alert("操作成功!");
            }
            else {
                window.alert("操作失败!错误信息:\n " + res.errors);
            }
        },
        error: ajaxError
    });
});

$("#p_select").change(function (e) {
    var tag = e.target;
    var index = tag.selectedIndex;
    if (index <= 0) {
        setSubSelects(-1);
        return;
    }
    var selectOp = tag.options[index];
    var obj = JSON.parse(selectOp.value);
    setSubSelects(obj.typeid);
});

function ajaxError(jqXHR, textStatus, errorThrown) {
    window.alert(`错误信息:
                          状态码: ${jqXHR.status} 
                          状态信息:${jqXHR.state()}
                          错误类型: ${textStatus} 
                          返回信息: ${errorThrown}`);
}

function manyUploaderChange(e) {
    var tag = e.target;
    var box = $(this).parent().parent().children(".uploader-box");
    var len = box.length;
    //获取索引
    var index = box.index($(this).parent());
    var reader = new FileReader();
    var issub = $(this).hasClass("sub-uploader");
    reader.readAsDataURL($(this)[0].files[0]);
    reader.onload = function () {
        $(tag).parent().addClass("selectOver");
        $(tag).prev().attr("src", this.result);
        $(tag).next(".close-btn").show();
        console.log("剩余长度:" + tag.files.length);
    }
    if (index == len - 1) {
        addUpLoaderBox(issub);
    }
}

function addUpLoaderBox(issub) {
    var label = document.createElement("label");
    var newidx = randomNum(0, 9999);
    var cls = issub ? "sub-uploader-" : "det-uploader-";
    do {
        newidx++;
    } while ($("#" + cls + newidx).length > 0);
    var newid = cls + newidx;
    label.innerHTML =
        ` <img src="#"  alt="商品展示图片" />
                <input accept=".jpeg,.jpg,.png" type="file" id="${newid}" class="${issub ? "sub-uploader" : "det-uploader"} uploader" />
                <i class="close-btn" title="移除">x</i>`
    $(label).attr("for", `${newid}`);
    label.className = "flex-center uploader-box";
    $(issub ? ".g-subimgs" : ".g-detimgs").append(label);
    $(label).children(".uploader").change(manyUploaderChange);
    $(label).children(".close-btn").click(closeBtnClick);
    return newid;
}

//生成从minNum到maxNum的随机数
function randomNum(minNum, maxNum) {
    switch (arguments.length) {
        case 1:
            return parseInt(Math.random() * minNum + 1, 10);
            break;
        case 2:
            return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
            break;
        default:
            return 0;
            break;
    }
} 

function closeBtnClick(e) {
    e.preventDefault();
    var tag = e.target;
    var isfir = $(tag).parent().hasClass("first");
    var $next = $(tag).parent().next(".uploader-box");
    var delArea = $(tag).parent().parent();
    var isSubArea = delArea.hasClass("g-subimgs");
    var isDetArea = delArea.hasClass("g-detimgs");
    //如果后面存在其他文件框则将此框表示为可删除
    if (isfir && $next.length > 0) {
        $next.addClass("first");
        $(tag).parent().removeClass("first");
        isfir = false;
    }
    //如果是第一框则移除文件,不进行删除
    if (isfir) {
        var dom = $(tag).parent().removeClass("selectOver").children(".uploader").get(0);
        dom.value = '';
    }
    else {
        $(this).parent().remove();
    }
    if (isChangeModel) {
        var src = $(this).prevAll("img").attr("src");
        if (isSubArea) SubDelFiles.push(src);
        if (isDetArea) DetDelFiles.push(src);
    }
}

//设置展示图片
function setMainUpLoader(src) {
    if (!src || src.length == 0) return;
    $("#main-img").attr("src", src).attr("filename", src).parent().addClass("selectOver").get(0);
}

//设置附属/详情图片集
function setManyloader(srcArr, issub = true) {
    if (!srcArr) return;
    if (srcArr.length === 0) return;
    var $dom = $(issub ? ".g-subimgs" : ".g-detimgs");
    $dom.children(".first").children("img").attr("src", srcArr[0]).attr("filename", getfileName(srcArr[0])).parent().addClass("selectOver");
    $dom.children(".first img").attr("filename");
    for (var i = 1; i < srcArr.length; i++) {
        var id = addUpLoaderBox(issub);
        $("#" + id).prev("img").attr("src", srcArr[i]).attr("filename", getfileName(srcArr[i])).parent().addClass("selectOver");
    }
    addUpLoaderBox(issub);
}

//返回文件名
function getfileName(src) {
    var strs = src.split("/");
    var fname = strs[strs.length - 1];
    return fname;
}

//根据父级的typeid设置父级默认选项
function setParentSelect(tid) {
    var doms = $("#p_select option:gt(0)");
    var $op;
    for (var i = 0; i < doms.length; i++) {
        var obj = JSON.parse(doms.get(i).value);
        if (obj.typeid == tid) {
            $op = $(doms.get(i));
            break;
        }
    }
    var idx = $op.index();
    $("#p_select")[0].selectedIndex = idx;
}

//根据父级id显示其下所有的子级分类
function setSubSelects(pid) {
    var $options = $("#s_select option:gt(0)").hide();
    $("#s_select")[0].selectedIndex = 0;
    var ops = [];
    for (var i = 0; i < $options.length; i++) {
        var op = $options.get(i);
        var obj = JSON.parse($(op).val());
        if (obj.parentid == pid) {
            ops.push(op);
        }
    }
    $(ops).show();
}

//设置子级分类,并联动其父级选项
function setSubTypeid(stid) {
    var $ops = $("#s_select option:gt(0)");
    var $op;
    var parentid = -1;
    for (var i = 0; i < $ops.length; i++) {
        var op = $ops.get(i);
        var obj = JSON.parse(op.value);
        if (obj.typeid == stid) {
            $op = $(op);
            parentid = obj.parentid;
            break;
        }
    }
    if (!$op) {
        console.log("没有找到typeid为" + stid + "的子类");
        return;
    }
    var idx = $op.index();
    setParentSelect(parentid);
    setSubSelects(parentid);
    $("#s_select")[0].selectedIndex = idx;
}

